﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using PluggableModulesInterface;
using StorageManagement;
using Settings;
using SMSROUTER.Business;
using Utils;
using PluggableModulesRouter;
using SMSROUTER.StorageManagement;

namespace MTRouterVTN
{
    public class Router : WorkingBaseMTWebServiceRouter
    {
        #region Properties and Fields
        private VTNServer_eMarketing.VTNServer_eMarketing _SmsRouterObject = new VTNServer_eMarketing.VTNServer_eMarketing();
        protected override System.Web.Services.Protocols.SoapHttpClientProtocol SmsRouterObject
        {
            get
            {
                return _SmsRouterObject;
            }
        }
        public string UserName
        {
            get
            {
                return GetConfig("UserName");
            }
            set
            {
                SetConfig("UserName", value);
            }
        }

        public string Password
        {
            get
            {
                return GetConfig("Password");
            }
            set
            {
                SetConfig("Password", value);
            }
        }

        public int DefaultMTTypeID
        {
            get
            {
                return int.Parse(GetConfig("DefaultMTTypeID"));
            }
            set
            {
                SetConfig("DefaultMTTypeID", value.ToString());
            }
        }

        public string DefaultCdrIndicator
        {
            get
            {
                return GetConfig("DefaultCdrIndicator");
            }
            set
            {
                SetConfig("DefaultCdrIndicator", value);
            }
        }

        public string DefaultSmpp_account
        {
            get
            {
                return GetConfig("DefaultSmpp_account");
            }
            set
            {
                SetConfig("DefaultSmpp_account", value);
            }
        }
        #endregion

        protected override void SendSms(List<SmsOutWaiting> smsList)
        {
            int threadId = ThreadID;
            bool logToText = this.EnableLogToText;
            try
            {
                if (smsList.Count > 0)
                {
                    using (DataSet ds = CreateDataSet(smsList))
                    {
                        string[][] insertResult = new string[][] { };
                        int iResult = (SmsRouterObject as VTNServer_eMarketing.VTNServer_eMarketing).eMarketting_Send_MT(Password, ds, ref insertResult);
                        if (insertResult.Length > 0 && insertResult[0].GetUpperBound(0) >= 0)
                        {
                            for (int j = 0; j < insertResult[0].Length; j++)
                            {
                                SmsOutWaiting sms = smsList.FirstOrDefault(item => item.SmsOutGUID != null && item.SmsOutGUID == Guid.Parse(insertResult[0][j]));
                                if (sms != null)
                                {
                                    if (string.Compare(insertResult[1][j], "TRUE", true) == 0)
                                    {
                                        SmsOutReportStorage.EnqueueElementData(Key, new SmsOutReportStruct(sms.RouterID, sms.SmsOutGUID, sms.CooperateGUID, DateTime.Now, DateTime.Now, sms.RetryOnFailReqTimes, sms.RetryOnTimeOutReqTimes, AppSetting.Status.SENTGATEWAY, threadId));
                                    }
                                    else
                                    {
                                        RetryOnFailure(sms, insertResult[1][j]);
                                    }
                                }
                            }
                        }
                        else
                        {
                            Log.InsertLog("insertResult.Length == 0", "MTRouterVTN.Router.SendSms", this.ObjectType, AppSetting.WarningType.mt_error, null);
                            RetryOnFailure<SmsOutWaiting>(smsList, "insertResult.Length == 0");
                        }
                        if (logToText)
                        {
                            if (insertResult.Length > 0)
                            {
                                Log.LogToTexts(insertResult[0], insertResult[1], AppSetting.RouterType.MTROUTER);
                            }
                            else
                            {
                                Log.LogToText(Guid.Empty, "insertResult.Length == 0", AppSetting.RouterType.MTROUTER);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                HandleException<SmsOutWaiting>(ex, AppSetting.WarningType.mt_error, smsList);
            }
        }

        private DataSet CreateDataSet(IEnumerable<SmsOutWaiting> source)
        {
            DataTable dt = new DataTable("SMSOut");
            #region create table scheama
            dt.Columns.Add("deliver_sm_id", typeof(string));
            dt.Columns.Add("submit_sm_id", typeof(string));
            dt.Columns.Add("date_time", typeof(DateTime));
            dt.Columns.Add("subs", typeof(string));
            dt.Columns.Add("dest_addr", typeof(string));
            dt.Columns.Add("vasp_num", typeof(string));
            dt.Columns.Add("msg_hex_body", typeof(string));
            dt.Columns.Add("num_of_concated", typeof(int));
            dt.Columns.Add("isBinary", typeof(string));
            dt.Columns.Add("operator_id", typeof(string));
            dt.Columns.Add("sms_out_ID", typeof(int));
            dt.Columns.Add("cdr_indicator", typeof(string));
            dt.Columns.Add("esm_class", typeof(int));
            dt.Columns.Add("gu_id", typeof(string));
            dt.Columns.Add("mo_guid", typeof(string));
            dt.Columns.Add("smpp_account", typeof(string));
            dt.Columns.Add("server_id", typeof(string));
            #endregion create table scheama

            #region Fill table data
            foreach (var item in source)
            {
                DataRow dr = dt.NewRow();
                dt.Rows.Add(dr);
                dr["deliver_sm_id"] = (item.DeliverSmId ?? -1).ToString();
                dr["submit_sm_id"] = (item.SubmitSmId ?? -1).ToString();
                dr["date_time"] = DateTime.Now;
                dr["subs"] = item.Subs ?? "";
                dr["dest_addr"] = item.DestAddr ?? "";
                dr["vasp_num"] = item.ShortCode ?? "";
                dr["msg_hex_body"] = string.IsNullOrEmpty(item.MessageHexBody) ? (item.Message ?? "").ToHex(Encoding.ASCII) : item.MessageHexBody;
                dr["num_of_concated"] = item.NumOfConcated ?? 0;
                dr["isBinary"] = item.IsBinary ?? "";
                dr["operator_id"] = Operator.GetOperatorGateWay(item.OperatorID);
                dr["sms_out_ID"] = -1;
                dr["cdr_indicator"] = item.CdrIndicator ?? DefaultCdrIndicator;
                dr["esm_class"] = item.EmsClass ?? 0;
                dr["gu_id"] = (item.SmsOutGUID ?? (object)"").ToString();
                dr["mo_guid"] = (item.SmsInGUID ?? (object)"").ToString();
                dr["server_id"] = (item.ServerID ?? -1).ToString();

                if (item.MTTypeID == null)
                    item.MTTypeID = DefaultMTTypeID; //2 mac dinh la ANNOUCEMENT
                SmsShortCode item_short_code = SmsShortCode.FindItem(obj => obj.CooperateID == item.CooperateID && obj.RouterID == item.RouterID && obj.ShortCode == item.ShortCode && obj.OperatorID == item.OperatorID && obj.MTTypeID == item.MTTypeID);
                if (item_short_code != null)
                    dr["smpp_account"] = item_short_code.SmppAccount ?? "";
                else
                    dr["smpp_account"] = DefaultSmpp_account;
            }
            #endregion
            DataSet retDs = new DataSet();
            retDs.Tables.Add(dt);
            return retDs;
        }
    }
}